﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebBrowserTest.AnalyzeResults;
using HtmlAgilityPack;

namespace WebBrowserTest.Analyzers
{
    public class AnchorAnalyzer : AbstractAnalyzer
    {
        private HtmlDocument _htmlDoc = new HtmlDocument();

        public override AbstractAnalyzeResult GetAnalyseResult(string html, string url)
        {
            //url = Utility.Utils.ExtractDomainNameFromUR(url);
            _htmlDoc.LoadHtml(html);
            var anchors = _htmlDoc.DocumentNode.SelectNodes("//a");
            if (anchors == null) return new AnchorAnalyzeResult{Anchor = ""};

            var anchor = anchors.Where(o => o.Attributes["href"] != null &&
                                               o.Attributes["href"].Value != null &&
                                                     o.Attributes["href"].Value.ToLower().Contains(
                                                         url.ToLower())).Select(
                                                             x => x.InnerText).Where(x=>x.Trim()!=string.Empty).FirstOrDefault();
            
            return new AnchorAnalyzeResult {Anchor = anchor == null?string.Empty:anchor.TrimEnd().TrimStart(),Date=DateTime.Now,DomainName = url};
        }
    }
}
